package com.fs.sys.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fs.sys.bean.dto.*;
import com.fs.sys.bean.enums.TenantStatus;
import com.fs.sys.bean.req.TenantAddReq;
import com.fs.sys.entityservice.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 租户服务
 *
 * @author LiuQi 2025/6/14-16:03
 * @version V1.0
 **/
@Service
public class TenantService {
    @Autowired
    private TenantEntityService tenantEntityService;

    @Autowired
    private UserEntityService userEntityService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TenantUserEntityService tenantUserEntityService;

    /**
     * 新增租户
     * @param req 请求参数
     */
    @Transactional
    public void add(TenantAddReq req) {
        String adminPhone = req.getAdmin().getPhone();
        String tenantId = IdWorker.getIdStr();

        // 根据手机号查找用户
        UserDTO admin = userEntityService.findByPhone(adminPhone).orElse(null);
        if (null == admin) {
            // 用户不存在，先添加用户
            admin = new UserDTO();
            admin.setNickname(Optional.ofNullable(req.getAdmin().getNickname()).orElse(req.getName()));
            admin.setUsername(adminPhone);
            admin.setPassword(passwordEncoder.encode(adminPhone.substring(5)));
            admin.setPhone(adminPhone);
            admin.setCurrentTenantId(tenantId);
            admin = userEntityService.insert(admin);
        }

        // 添加租户用户关系
        TenantUserDTO tenantUser = new TenantUserDTO();
        tenantUser.setTenantId(tenantId);
        tenantUser.setUserId(admin.getId());
        tenantUserEntityService.insert(tenantUser);

        // 添加租户
        TenantDTO tenant = new TenantDTO();
        BeanUtils.copyProperties(req, tenant);
        tenant.setId(tenantId);
        tenant.setAdminId(admin.getId());
        tenant.setStatus(TenantStatus.VALID);
        tenant = tenantEntityService.insert(tenant);

        // 添加默认系统配置
        SysConfigDTO sysConfigDTO = new SysConfigDTO();
        sysConfigDTO.setCode("sysConfig");
        sysConfigDTO.setName("sysConfig");
        sysConfigDTO.setId("sysConfig-" + tenantId);
        sysConfigDTO.setValue("{\"showTopMenus\": true, \"showTagsTab\": false}");
    }
}
